package com.buddy.learn.spring.mvc.demo.controller;

import com.buddy.learn.spring.mvc.annotation.BAutowired;
import com.buddy.learn.spring.mvc.annotation.BController;
import com.buddy.learn.spring.mvc.annotation.BRequestMapping;
import com.buddy.learn.spring.mvc.annotation.BRequestParam;
import com.buddy.learn.spring.mvc.demo.service.IModifyService;
import com.buddy.learn.spring.mvc.demo.service.IQueryService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@BController
@BRequestMapping("/web")
public class MyAction {

    @BAutowired
    private IQueryService queryService;
    @BAutowired
    private IModifyService modifyService;

    @BRequestMapping("/search/*.json")
    public void search(HttpServletRequest request, HttpServletResponse response,
                       @BRequestParam("name") String name) {
        String result = queryService.search(name);
        out(response, result);
    }


    @BRequestMapping("/add.json")
    public void add(HttpServletRequest request, HttpServletResponse response,
                    @BRequestParam("name") String name,
                    @BRequestParam("addr") String addr) {
        String result = modifyService.add(name, addr);
        out(response, result);
    }


    @BRequestMapping("/remove.json")
    public void remove(HttpServletRequest request, HttpServletResponse response,
                       @BRequestParam("id") Integer id) {
        String result = modifyService.remove(id);
        out(response, result);
    }


    private void out(HttpServletResponse response, String str) {
        try {
            response.getWriter().write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
